package com.coocaa.ops.admin.v1.timedtask.schedule;

import com.coocaa.ops.admin.base.language.CommonLanguageProperties;
import com.coocaa.ops.admin.v1.audit.service.AuditTaskProviderManager;
import com.coocaa.ops.admin.v1.auth.sys.biz.impl.SysUserBizImpl;
import com.coocaa.ops.admin.v1.timedtask.biz.TimedTaskBizImpl;
import com.coocaa.ops.common.core.base.enums.ResourceStatusEnums;
import com.coocaa.ops.common.core.base.enums.ResourceTypeEnum;
import com.coocaa.ops.common.core.biz.timedtask.entity.TimedTaskInfoEntity;
import com.coocaa.ops.common.tool.base.InstanceUtil;
import com.coocaa.ops.common.tool.date.DateUtil;
import com.coocaa.ops.common.tool.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @Author : bijiahao
 * @Date : 2018/1/11.
 * @Description:<p> 定时任务过期 没有执行时的 防护处理</p>
 */
@Slf4j
@Component
public class TimedQuartzJobTask {
    @Autowired
    private TimedTaskBizImpl timedTaskBiz;
    @Autowired
    private AuditTaskProviderManager auditTaskProviderManager;
    //    @Autowired
//    private MultiCenterCacheUpdateService multiCenterCacheUpdateService;
//    @Autowired
//    private SendEmailServiceImpl sendEmailService;
//    @Autowired
//    private SystemProperties systemProperties;
    @Autowired
    private SysUserBizImpl sysUserBiz;

    private static CommonLanguageProperties commonLanguageProperties;


    /**
     * 设置每天的凌晨2点47和5点47 触发
     */
//    @Scheduled(cron = "0 47 2,5 * * ?")
    public void monitorTimedTask() {

    }

    /**
     * 每隔13分钟-晚上22点到深夜23点 触发
     */
//    @Scheduled(cron = "0 0/13 22-23 * * ?")
    public void monitorTimedTaskForDeepNight() {
        handleTimedTask();
    }

    /**
     * 每隔23分钟-凌晨0点到早上10点 触发
     */
//    @Scheduled(cron = "0 0/23 0-20 * * ?")
    public void monitorTimedTaskForBeforeDownAndMorning() {
        handleTimedTask();
    }

    /**
     * 处理定时任务
     */
    private void handleTimedTask() {
//        if (null != systemProperties.getEnableInitTimedJob() && systemProperties.getEnableInitTimedJob()) {
//            QueryTemplate<TimedTaskInfoEntity> wrapper = QueryTemplate.getQueryTemplate();
//            wrapper.eq("status", ResourceStatusEnums.AUDITED_NOT_ON_LINE.getStatus());
//            List<TimedTaskInfoEntity> taskInfoList = timedTaskBiz.getMapper().selectList(wrapper);
//            if (CollectionUtils.isEmpty(taskInfoList)) {
//                log.debug("\n==== 版面板块定时上架-定时任务 当前没有要执行的定时任务");
//                return;
//            }
//            for (TimedTaskInfoEntity timedTask : taskInfoList) {
//                handleEachTimedTask(timedTask);
//            }
//        }
    }


    /**
     * 处理每一个定时任务
     *
     * @param timedTask
     */
    private void handleEachTimedTask(TimedTaskInfoEntity timedTask) {
        long currentTime = System.currentTimeMillis();
        Date releaseDate = timedTask.getReleaseTime();
        long releaseTime = releaseDate.getTime();
        if (releaseTime > currentTime) {
            //如果定时时间还没到
            log.debug("\n==== 版面板块定时上架-定时任务 定时时间还没到....");
            return;
        }
        //如果定时时间已到
        TimedTaskInfoEntity update = new TimedTaskInfoEntity();
        update.setId(timedTask.getId());
        update.setStatus(ResourceStatusEnums.ON_LINE.getStatus());
        timedTaskBiz.updateById(update);
        //上架操作
        auditTaskProviderManager.putShelves(timedTask.getResourceId(), timedTask.getResourceVersion(), timedTask.getCurrentOperator(), timedTask.getResourceType());
        //更新缓存
//        multiCenterCacheUpdateService.updateMultiCenterCache(timedTask.getResourceId(), timedTask.getResourceType());


    }

    /**
     * 发送邮件-V2版本
     *
     * @param timedTask
     */
    private void sendEmailV2(TimedTaskInfoEntity timedTask) {
        log.info(getLogInfo(timedTask));
        String subject = getSubjectV2();
        String content = getContentV2(timedTask);
        String auditUserEmail = sysUserBiz.getEmailByUserId(timedTask.getCurrentOperator());
        List<String> emails = InstanceUtil.newArrayList(1);
        emails.add(auditUserEmail);
//        sendEmailService.sentEmailForClock(subject, content, emails);
    }

    /**
     * 获取邮件内容-V2版本
     *
     * @param timedTask
     * @return
     */
    private String getContentV2(TimedTaskInfoEntity timedTask) {
        StringBuilder sb = new StringBuilder();
        sb.append("\tHomepage platform timing task-remedial performance:")
                .append("\n\t<1>Resource type: ")
                .append(getResourceTypeCnName(timedTask.getResourceType()))
                .append("\n\t<2>Resource ID: ")
                .append(timedTask.getResourceId())
                .append("\n\t<3>Resource Edition ")
                .append(timedTask.getResourceVersion())
                .append("\n\t*The original execution time is: ")
                .append(DateUtil.date2Str("yyyy-MM-dd HH:mm:ss", timedTask.getReleaseTime()))
                .append("\n\t*The current remedial execution time is: ")
                .append(DateUtil.date2Str("yyyy-MM-dd HH:mm:ss", timedTask.getLastUpdateDate()))
        ;
        return sb.toString();
    }

    private String getLogInfo(TimedTaskInfoEntity timedTask) {
        StringBuilder info = new StringBuilder();
        info.append("\n====Timed task-remedial execution completed:")
                .append("\n\t<1>Resource type: ")
                .append(timedTask.getResourceType())
                .append("\n\t<2>Resource ID: ")
                .append(timedTask.getResourceId())
                .append("\n\t<3>Resource Edition: ")
                .append(timedTask.getResourceVersion());
        return info.toString();
    }


    /**
     * 获取资源类型-中文名称
     *
     * @param resourceType
     * @return
     */
    private String getResourceTypeCnName(String resourceType) {
        if (ResourceTypeEnum.PANEL.getValue().equals(resourceType)) {
            return "Panel";
        } else if (ResourceTypeEnum.TAB.getValue().equals(resourceType)) {
            return "Tab";
        }
        throw new BusinessException(null, commonLanguageProperties.getNotTreat());
    }

    @Autowired
    public void setCommonLanguageProperties(CommonLanguageProperties commonLanguageProperties) {
        TimedQuartzJobTask.commonLanguageProperties = commonLanguageProperties;
    }

    /**
     * 获取邮件主题-V2版本
     *
     * @return
     */
    private String getSubjectV2() {
        StringBuilder sb = new StringBuilder();
        sb.append("Home platform timed tasks-remedial execution results");
        return sb.toString();
    }
}
